package com.sansui.blog.config;

import com.sansui.blog.pojo.User;
import com.sansui.blog.pojo.sys.SysMenu;
import com.sansui.blog.service.SysMenuService;
import com.sansui.blog.service.SysRoleService;
import com.sansui.blog.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @name: AuthRealm
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-07-31 19:10
 *
 * AuthRealm
 **/
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User sysUser = (User) principals.fromRealm(this.getClass().getName()).iterator().next();

        // 赋予角色
        User sysMenu = (User)principals.getPrimaryPrincipal();
        String userId = sysMenu.getUsername();
        List<String> listRole = sysRoleService.byUserNameQueryRole(userId);
        for (String str : listRole) {
            info.addRole(str);
        }

        List<SysMenu> listMenu = sysMenuService.byUserNameQueryMenu(userId);
        //根据用户账号查询所有菜单
        if (!org.springframework.util.CollectionUtils.isEmpty(listMenu)) {
            Set<String> permissionSet = new HashSet();
            for (SysMenu menu : listMenu) {
                String permission = null;
                if (!StringUtils.isEmpty(permission = menu.getPermission())) {
                    permissionSet.addAll(Arrays.asList(permission.trim().split(",")));
                }
            }
            info.setStringPermissions(permissionSet);
        }
        return info;
    }

    /**
     * 认证登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //从浏览器地址栏获取用户名
        String username = usernamePasswordToken.getUsername();
        User user = userService.findByUsername(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
    }

}
